/*
 * 智能开窗模块
获取窗户当前位置百分比
{
  "method": "get",
  "obj": ["window_percent"]
}

第一次初始化
{
  "method": "set",
  "window": "init"
}
向左移动
{
  "method": "set",
  "window": "left"
}
向右移动
{
  "method": "set",
  "window": "right"
}
停止移动
{
  "method": "set",
  "window": "OFF"
}
 */
#include "Arduino.h"    
#include <string.h>
#include <OneButton.h>       
#include <WiFi.h>
#include <sddc.h>
#include <cJSON.h>
#include <Wire.h>
#include <SDDC_SDK_lib.h>


#define SDDC_CFG_PORT             680U             // SDDC 协议使用的端口号
#define PIN_INPUT                 0                // 选择 IO0 进行控制
#define ESP_TASK_STACK_SIZE       4096
#define ESP_TASK_PRIO             25

#define WINDOW_STATE_RIGHT        1
#define WINDOW_STATE_LEFT         0
#define WINDOW_ON                 1
#define WINDOW_OFF                0
#define WINDOW_PERCENT            "window_percent"


static int window_state           = 0;
static int window_direction       = 0;
static double window_percent      = 0;
static sddc_t *g_sddc;
static const char* ssid           = "EOS-Tenda";         // WiFi 名
static const char* password       = "1234567890";        // WiFi 密码

static const int window2_pin      = 25;                 // 电机方向的控制引脚
static const int window1_pin      = 26;                 // 电机方向的控制引脚
static const int off_pin          = 27;                 // 电机启停的控制引脚


OneButton button(PIN_INPUT, true);

sddc_bool_t window_percent_get(char *objvalue, int value_len)
{
    sprintf(objvalue, "%lf", window_percent);
    return SDDC_TRUE;
}

static void dev_report_state()
{
    cJSON * root = cJSON_CreateObject();
    cJSON * array = cJSON_CreateArray();
    cJSON_AddItemToArray(array, cJSON_CreateString(WINDOW_PERCENT));
    cJSON_AddItemToObject(root, "obj", array);
    object_report(root);
}

static void window_percent_task(void *arg) {
    while(1) {
        if (window_state) {
            if (window_direction == 1 && window_percent < 100) {
                window_percent++;
            } else if (window_direction == 0 && window_percent > 0) {
                window_percent--;
            }
            if (window_percent == 0 || window_percent == 100) {
                sddc_printf("停止移动！\n");
                digitalWrite(off_pin, LOW);
                digitalWrite(window1_pin, LOW);
                digitalWrite(window2_pin, LOW);
                window_state = WINDOW_OFF;
            }
            dev_report_state();
        }
        delay(200);
    }
}

sddc_bool_t window_percent_set(const uint64_t value)
{
    window_percent = value;
    return SDDC_TRUE;
}

/*
 * 开窗控制函数
 */
sddc_bool_t window_set(const char* value)
{
    if (!strcmp(value,"left") && window_percent > 0) {
        digitalWrite(off_pin, LOW);
        digitalWrite(window1_pin, HIGH);
        digitalWrite(window2_pin, HIGH);
        window_direction = WINDOW_STATE_LEFT;
        window_state = WINDOW_ON;
        if (digitalRead(window1_pin) == 1 && digitalRead(window2_pin) == 1) {
          digitalWrite(off_pin, HIGH);
          sddc_printf("向左移动！\n");
        } else {
            sddc_printf("短路警告！！！\n");
            digitalWrite(off_pin, LOW);
        }
    } else if (!strcmp(value,"right") && window_percent < 100) {
        digitalWrite(off_pin, LOW);
        digitalWrite(window1_pin, LOW);
        digitalWrite(window2_pin, LOW);
        window_direction = WINDOW_STATE_RIGHT;
        window_state = WINDOW_ON;
        if (digitalRead(window1_pin) == 0 && digitalRead(window2_pin) == 0) {
          digitalWrite(off_pin, HIGH);
          sddc_printf("向右移动！\n");
        } else {
            sddc_printf("短路警告！！！\n");
            digitalWrite(off_pin, LOW);
        }
     } else if (!strcmp(value,"OFF")) {
         sddc_printf("停止移动！\n");
         digitalWrite(off_pin, LOW);
         digitalWrite(window1_pin, LOW);
         digitalWrite(window2_pin, LOW);
         window_state = WINDOW_OFF;
     } else if (!strcmp(value,"init")) {
          sddc_printf("init！\n");
     }
     return SDDC_TRUE;
}

/* 
 *  数字量设备对象函数与处理方法注册
 */
NUM_DEV_REGINFO num_dev[] = {
        {"window_percent",window_percent_set},
};

/*
 *  显示设备对象函数与处理方法注册
 */
DIS_DEV_REGINFO dis_dev[] = {
};

/*
 * IO设备对象设置函数与处理方法注册
 */
IO_DEV_REGINFO io_dev[] = {
        {"window",window_set},
};

/*
 *  系统对象状态获取注册
 */
DEV_STATE_GET  dev_state_get_reg[] = {
//        {"window",   DEV_IO_TYPE,  window_get},
        {"window_percent", DEV_NUM_TYPE, window_percent_get},
};

/*
 *  当前设备的信息定义
 */
DEV_INFO    dev_info = {
            .name     = "智能开窗器",
            .type     = "device.window",
            .excl     = SDDC_FALSE,
            .desc     = "ESP-32S",
            .model    = "IDWINDOW01B",
            .vendor   = "inspiration-desktop",
};

/*
 *   系统注册对象汇聚
 */
SDDC_CONFIG_INFO sys_cfg = {
        .token             = "1234567890",            // 设备密码
        .devinfo           = &dev_info,               
        .io_dev_reg        = io_dev,
        .io_dev_reg_num    = ARRAY_SIZE(io_dev),
        .num_dev_reg       = num_dev,
        .num_dev_reg_num   = ARRAY_SIZE(num_dev),
        .state_get_reg     = dev_state_get_reg,
        .state_get_reg_num = ARRAY_SIZE(dev_state_get_reg),
        .dis_dev_reg       = dis_dev,
        .dis_dev_num       = ARRAY_SIZE(dis_dev),
};


/*
 * IO0 按键检测任务
 */
static void esp_io0_key_task()
{
    WiFi.disconnect();
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println("WIFI Wait for Smartconfig");
        
        // 设置为Station模式
        WiFi.mode(WIFI_STA);
        
        // 开始智能配网
        WiFi.beginSmartConfig();
        while (1)
        {
            delay(500);
            // 检查智能配网
            if (WiFi.smartConfigDone())
            {
                // 设置自动连接
                WiFi.setAutoConnect(true);  
                break;
            }
        }
    }
}
/*
 * 循环扫描按键
 */
static void esp_tick_task(void *arg)
{
    void *sddc = arg;
    (void)sddc;
    while(1)
    {
        button.tick();
        delay(100);
    }
}

/*
 * 初始化控制模块
 */
void sensor_init()
{
    // 初始化IO口，设置为输出模式
    pinMode(window2_pin, OUTPUT);
    pinMode(window1_pin, OUTPUT);
    pinMode(off_pin, OUTPUT);
  
    // 为了防止短路，所有IO全部拉低
    digitalWrite(window2_pin, LOW);
    digitalWrite(window1_pin, LOW);
    digitalWrite(off_pin, LOW);
    // 创建开窗控制线程
    xTaskCreate(window_percent_task, "window_percent_task", ESP_TASK_STACK_SIZE, NULL, ESP_TASK_PRIO, NULL);

}

void setup() {
    byte mac[6];
    Serial.begin(115200);
    Serial.setDebugOutput(true);
    Serial.println();

    // 初始化控制模块
    sensor_init();

    // 清除一下按键状态机的状态
    button.reset();
  
    // 创建按键扫描线程，长按 IO0 按键，松开后ESP32 将会进入 SmartConfig 模式
    sddc_printf("长按按键进入 Smartconfig...\n");
    button.attachLongPressStop(esp_io0_key_task);
    xTaskCreate(esp_tick_task, "button_tick", ESP_TASK_STACK_SIZE, NULL, ESP_TASK_PRIO, NULL);
    
    // 启动 WiFi 并且连接网络
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) 
    {
        delay(500);
        Serial.print(".");
    }
  
    // 获取并打印 IP 地址
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("'ip :");
    Serial.print(WiFi.localIP());
    Serial.println("' to connect");

    // sddc协议初始化
    sddc_lib_main(&sys_cfg);

    // 获取并打印网卡 mac 地址
    WiFi.macAddress(mac);
    sddc_printf("MAC addr: %02x:%02x:%02x:%02x:%02x:%02x\n",
              mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
    // 使用网卡 mac 地址设置设备唯一标识 UID
    sddc_set_uid(G_sddc, mac);
}

void loop() {
    // 运行 SDDC 协议循环
    while (1) 
    {
        sddc_printf("SDDC running...\n");
        sddc_run(G_sddc);
        sddc_printf("SDDC quit!\n");
    }

    // 销毁 SDDC 协议
    sddc_destroy(G_sddc);
}
